#encoding=utf-8
from __future__ import division

import sys
import os
import datetime
import time
import math
import ujson
import uuid
import urllib
import random,re
import traceback
from django.db import transaction
from urlparse import urlparse, parse_qsl

import requests
from django.contrib import auth
from django.template import RequestContext
from django.core.cache import cache
from django_redis import get_redis_connection
from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.db.models import Count, Max, F, Q,Min,Sum
from django.contrib.auth.decorators import login_required

from andy_manager import settings
import websys.webconfig as webconfig
from websys.models import (
UserInfo,BannerInfo,TableInfo,GameInfo,Feedback,GameRecord,RoomInfo,WithholdInfo,UserExpand,UserConsumeRecord,
ServerInfo,PlatformInfo,AgentInfo,AgentTableReport
)

import  websys.fun as fun
import  websys.ReturnCode as errcode
import record_redis
from websys import db_redis

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
                    #玩家登陆
                    url(r'^platform_login', 'websys.view.mjhall.user_platformlogin', name='user_platformlogin'),
                       url(r'^account_login', 'websys.view.mjhall.user_accountlogin', name='user_accountlogin'),
                       url(r'^account_reg', 'websys.view.mjhall.user_accountregister', name='user_accountregister'),
                       url(r'^userinfo', 'websys.view.mjhall.user_getinfo', name='user_getinfo'),
                       url(r'^getusergameinfo', 'websys.view.mjhall.user_getgameinfo', name='user_getgameinfo'),
                       url(r'^awarduser', 'websys.view.mjhall.user_award', name='user_award'),
                       url(r'^useradd', 'websys.view.mjhall.user_addmore', name='user_addmore'),
                       #开房间,加入房间，作实（撤销）房间
                    url(r'^createroom', 'websys.view.mjhall.user_createroom', name='createroom'),
                       url(r'^costfront', 'websys.view.mjhall.user_joinroom', name='joinroom'),
                       url(r'^costoprate', 'websys.view.mjhall.user_operateroom', name='operateroom'),
                       url(r'^roomover', 'websys.view.mjhall.user_roomover', name='roomover'),
                       url(r'^findroom', 'websys.view.mjhall.user_findroom', name='findroom'),
                       url(r'^roominfo', 'websys.view.mjhall.user_getroominfo', name='roominfo'),
                       url(r'^saveroomostatus', 'websys.view.mjhall.user_saveroomstatus', name='saveroomostatus'),
                       url(r'^addmoneyrecord', 'websys.view.mjhall.user_addmoneyrecord', name='addmoneyrecord'),
                       #***消息
                       url(r'^msglist', 'websys.view.mjhall.user_getMSG', name='msglist'),
                       url(r'^readmsg', 'websys.view.mjhall.user_readMSG', name='msglist'),
                       #当局结算
                    url(r'^gamesettle', 'websys.view.mjhall.user_gamesettle', name='gamesettle'),
                       #banner列表
                    url(r'^banner', 'websys.view.mjhall.hall_bannerlist', name='banner'),
                       #记录相关
                    url(r'^totalrecord', 'websys.view.mjhall.user_totalrecord', name='user_totalrecord'),
                    url(r'^gamerecord', 'websys.view.mjhall.user_gamerecord', name='user_gamerecord'),
                    url(r'^recorddetail', 'websys.view.mjhall.user_recorddetail', name='user_recorddetail'),
                       #反馈
                    url(r'^feedback', 'websys.view.mjhall.user_feedback', name='feedback'),
                       url(r'^getfeedback', 'websys.view.mjhall.user_getfeedback', name='getfeedback'),
                    #url(r'^test', 'websys.view.mjhall.test', name='test'),

                         #其它。。。。。。。。。。。。。
                       url(r'^yl_realname', 'websys.view.mjhall.set_realname', name='set_realname'),

    )

#
# DROP TABLE websys_userrecharge;
# DROP TABLE websys_userexpand;
# DROP TABLE websys_userconsumerecord;
# DROP TABLE websys_feedback;
# DROP TABLE websys_gamerecord;
# DROP TABLE websys_withholdinfo;
# DROP TABLE websys_withdrawrecord;
# DROP TABLE websys_commissionreport;
# DROP TABLE websys_tableinfo;

#获取banner,
#http://127.0.0.1:8080/api/hall/bannerlist?a=10
@csrf_exempt
def hall_bannerlist(request):
    #t_obj=fun.Decode_Request_MJ(request)
    #fun.add_log(t_obj)
    #print(request)
    t_appid = request.GET.get('appid',None)

    t_uid=None

    if t_appid:
        db_arr=BannerInfo.objects.filter(app__pf_id=t_appid).order_by('-id')
    else:
        db_arr=BannerInfo.objects.all().order_by('-id')#.values("")
    t_data=[]
    #返回值

    for ii in db_arr:
        #print(ii.url,'---***----',ii.img.url)
        t_data+=[{"url":ii.url,"img": fun.GetImgURL(request,ii.img.url)}]
    t_res={'code':0,'data':t_data}

    response = HttpResponse(ujson.dumps(t_res))
    return  response

#用户结算
#http://127.0.0.1:8080/api/hall/gamesettle?gameid=1&roomid=742053&roundid=1&data=[[1,100],[2,-10]]&ts=1495620335.797&writeid=0c60998f-3fb4-11e7-9a8f-ea79fe8fbc52
# gameid u'游戏编号'
# roomid u'房间号'
# roundid u'局号'
#data [[玩家1帐号，分数],[....]]
#ts u'时间截'
@csrf_exempt
def user_gamesettle(request):
    t_obj=fun.Decode_Request_MJ(request,True)
    fun.add_log(t_obj)

    t_bid=None
    t_res={'code':-1,'msg':'','recordid':""}
    if request.method == 'GET':
        need_keys=['roundid','gameid','roomid','data','ts','writeid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))
        t_bid = t_obj['roundid']
        t_gid=int(t_obj['gameid'])
        t_rid=t_obj['roomid']
        t_data=ujson.loads(t_obj['data'])
        t_time=float(t_obj['ts'])
        t_recordid=t_obj['writeid']
    elif request.method == 'POST':
        t_bid = request.POST.get('roundid',None)

    if not t_bid:
        t_res['msg']="empty roundid"
        return HttpResponse(ujson.dumps(t_res))

    #判断是否存在
    #if(GameRecord.objects.filter(roomid=t_rid,roundid=t_bid,recordid=t_recordid).exists()):
    #print(t_rid,'----','round__gte=',t_bid,'recordid=',t_recordid)
    if(TableInfo.objects.filter(roomid=t_rid,round__gte=t_bid,recordid=t_recordid).exists()):
        t_res['msg']="exists roundid"
        return HttpResponse(ujson.dumps(t_res))
    else:#写记录
        #game_obj=GameInfo.objects.get(pk=t_gid)
        try:
            tb_info=TableInfo.objects.get(roomid=t_rid,recordid=t_recordid)
            name_arr=[]
            uid_arr=[]
            t_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(t_time))
            with transaction.commit_on_success():
                #t_data=[玩家编号，分数，【统计类型1，统计类型2】,,,,,,,]
                for ii in t_data:
                    cur_pkid=int(ii[0])
                    cur_score=ii[1]
                    gr=GameRecord()
                    gr.gameid_id=t_gid
                    u_obj=UserInfo.objects.get(pk=cur_pkid)
                    gr.uid=u_obj
                    gr.nickname=u_obj.nickname
                    gr.roomid=t_rid
                    gr.roundid=t_bid
                    gr.score=cur_score
                    gr.start_time=t_time
                    gr.recordid=t_recordid
                    gr.save()
                    name_arr.append(u_obj.nickname)
                    uid_arr.append(cur_pkid)
                    #写入redis
                    record_redis.UserSettlement(cur_pkid,t_gid,t_rid,cur_score)
                    #游戏汇总表
                    if len(ii)>2:
                        #总局数
                        uCount=UserExpand.objects.filter(uid_id=cur_pkid,game_id=t_gid,typeid=0).count()
                        if uCount>0:
                            ue=UserExpand.objects.get(uid_id=cur_pkid,game_id=t_gid,typeid=0)
                            ue.amount+=1
                        else:
                            ue=UserExpand()
                            ue.uid_id=cur_pkid
                            ue.game_id=t_gid
                            ue.typeid=0
                        ue.save()
                        for ty in ii[2]:
                            if UserExpand.objects.filter(uid_id=cur_pkid,game_id=t_gid,typeid=ty).exists():
                                ue=UserExpand.objects.get(uid_id=cur_pkid,game_id=t_gid,typeid=ty)
                                ue.amount+=1
                            else:
                                ue=UserExpand()
                                ue.uid_id=cur_pkid
                                ue.game_id=t_gid
                                ue.typeid=ty
                            ue.save()

                #更新游戏的状态，开始时间,userlist=','.join(name_arr)
                tb_info.round=t_bid
                if int(t_bid)==1:
                    tb_info.game_time=t_time
                    #TableInfo.objects.filter(gameid_id=t_gid,roomid=t_rid).update(game_status=4,round=1,game_time=t_time)
                tb_info.save()
                fee_room_user(tb_info,uid_arr)
                #TableInfo.objects.filter(gameid_id=t_gid,roomid=t_rid,recordid=t_recordid).update(round=t_bid)
            #返回值
            t_res["code"]=0
            t_res["recordid"]=t_recordid
        except:
            fun.add_log_err(traceback.format_exc())#后期人工调用
            t_res['code']=errcode.Success#errcode.DB_Error

        fun.add_log(t_res)
        response = HttpResponse(ujson.dumps(t_res))
        return  response

#某个房间是否要扣参与者的费用
def fee_room_user(tb_model,arr_uid):
    t_type=tb_model.gameid.feetype
    print t_type,'--fee_room_user--',arr_uid
    if t_type==1:#扣参与者的
        pass

#****************************************房间相关***********************************************
#平台对应表{nhmj123:[1,2,3,4],qsmj123:[10,11,12]}
#global服务拉起时获取
global app2games
app2games={}
#根据平台获取游戏列表
def get_PlatformInfo_Games(_appid='nhmj123'):
    global app2games
    if not app2games:#读取数据库
        t_datas=PlatformInfo.objects.all()
        for ii_pi in t_datas:
            app2games[ii_pi.pf_id]=ii_pi.games.split(',')
        print '--get_PlatformInfo_Games--',app2games
    return  app2games.get(_appid,[])
get_PlatformInfo_Games()
#根据游戏id获取平台
def get_PlatformInfo_ID(_gameid):
    tmp_appid=None
    global app2games
    for ii_app in app2games:#遍历
        tmp_arr=app2games[ii_app]
        if str(_gameid) in tmp_arr:
            tmp_appid=ii_app
            break
    return  tmp_appid

#发现房间
#http://127.0.0.1:8080/api/hall/findroom?uid=1&appid=nhmj123
# uid u'用户帐号'
@csrf_exempt
def user_findroom(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    t_appid=None
    if request.method == 'GET':
        if 'uid' not in t_obj:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_appid=t_obj.get('appid',None)

    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty http uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

    #根据appid获取游戏列表
    t_games=None
    if t_appid:
        t_games=get_PlatformInfo_Games(t_appid)
    # if not t_games:
    #     t_data['msg']="empty games"
    #     t_data['code']=errcode.DB_DataNotExists
    #     return HttpResponse(ujson.dumps(t_data))

    #判断用户是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        #u_info=UserInfo.objects.get(pk=t_uid)
        #获取全部的正常桌
        date_to=datetime.datetime.now()
        date_from=fun.GetTime_ByNow(-1)
        if t_games!=None:
            tbs=TableInfo.objects.filter(gameid_id__in=t_games,game_status__in=webconfig.ROOM_NORMAL_STATUS,create_time__range=(date_from,date_to)).order_by('-id')
        else:
            tbs=TableInfo.objects.filter(game_status__in=webconfig.ROOM_NORMAL_STATUS,create_time__range=(date_from,date_to)).order_by('-id')
        t_create=[]
        t_join=[]
        for ii in tbs:
            cur_obj={'gameId':ii.gameid_id,'roomId':ii.roomid,'startTs':-1,'time':ii.time,'point':ii.point,'gamestatus':ii.game_status,'writeid':ii.recordid}
            cur_obj['recordid']=ii.round and ii.recordid or ""
            #是否开始了
            cur_obj['startTs']=DateTimeToTimetuple(ii.game_time)
            #游戏服务器ip,port
            t_freeserver=ii.server
            t_host=''
            t_port=0
            if t_freeserver:
                t_host=t_freeserver.ip
                t_port=t_freeserver.port
            cur_obj['host']=t_host
            cur_obj['port']=t_port
            cur_obj['createTs']=DateTimeToTimetuple(ii.create_time)
            cur_obj['playnum']=ii.playnum
            cur_obj['agent_id']=user_get_agent_id(ii.uid)
            cur_obj["openparam"]=ii.openparam
            cur_obj["round"]=ii.round
            cur_obj["agentId"]=ii.agentid_id or -1
            cur_obj['createtype']=ii.create_type or 0
            if ii.uid_id==int(t_uid):
                #cur_obj['createTs']=DateTimeToTimetuple(ii.create_time)
                t_create.append(cur_obj)
            elif cur_obj['startTs']>0 and WithholdInfo.objects.filter(uid_id=t_uid,tableid_id=ii.id).exists():#开局的才显示
                t_join.append(cur_obj)
        t_data['data']['create']=t_create
        t_data['data']['join']=t_join
        t_data['code']=0

        fun.add_log(t_data)

        return HttpResponse(ujson.dumps(t_data))
    else:#新增
        t_data['msg']="empty uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

#处理过期的房间列表
def handle_timeout_table(game_id,fee_type):
    #过滤超时的房间
    date_min=datetime.datetime.now()+datetime.timedelta(0,-webconfig.TIMEOUT_ROOM_HOUR*60*60)
    cur_filter=TableInfo.objects.filter(game_status__in=webconfig.ROOM_NORMAL_STATUS,create_time__lte=date_min,gameid_id=game_id)
    if fee_type==0:#只扣房主的
        for ii_item in cur_filter:
            if ii_item.round==0 or not ii_item.game_time:#没开打，要返回钱房卡
                t_point=ii_item.point
                if t_point<=0:
                    continue
                t_user=ii_item.uid
                t_user.gamepoint+=t_point
                t_ok=t_user.save()
                print ii_item.pk,ii_item.roomid,'--handle_timeout_table---',t_point,'--user--',t_user
    #更新数据库
    cur_filter.update(status=1,game_status=3)

#用户开房间
#http://127.0.0.1:8080/api/hall/createroom?uid=1&gameid=1&num=10&playtype=1&playnum=123
#代开createroom?gameid=54&uid=75&openparam=%7B"542"%3A0%2C"541"%3A6%7D&sign=17b9d969daf83203f98c45ad54274692&create_type=1
# uid u'用户帐号'
# gameid u'游戏编号'
# num u'时间'
# playtype u'类型'
#create_type开房类型，0默认，1代开
#返回{'code':-1,'msg':'','data':{'need_diamond':需要房卡,'diamond':剩余房卡},'params':[]}
#返回值用默认开房的那些
@csrf_exempt
def user_createroom(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{},'params':[]}
    if request.method == 'GET':
        need_keys=['uid','gameid','openparam']#num,'playtype','playnum']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_gid=int(t_obj['gameid'])
        t_num=t_obj.get('num',0)
        #宁海的
        t_type=t_obj.get('playtype','1')
        t_playnum=t_obj.get('playnum',-1)
        #新的
        t_openparam=t_obj.get('openparam','{}')
        t_agent=t_obj.get('agentid',-1)
        #开房模式
        t_create_type=t_obj.get('create_type',0)
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty http uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

    #获取唯一的房间号,测试是时间截
    t_roomid=0
    t1=str(time.time()).replace('.','')
    t_roomid=int(t1[-6:])

    t_roomstatus=webconfig.ROOM_NORMAL_STATUS
    #,数据库获取唯一的，7天内的game_status__in=[0,4],后期不按游戏分,gameid_id=t_gid
    t_roomid=fun.GetRandom()
    tm_start=fun.GetTime_ByNow()
    is_in=True
    while is_in:
        cur_num=TableInfo.objects.filter(create_time__gte=tm_start,roomid=t_roomid).count()
        if(cur_num==0):
            is_in=False
        else:
            t_roomid=fun.GetRandom()

    #获取随机一个空闲的游戏服务器,后期过滤忙的机器ip
    t_sers=ServerInfo.objects.filter(game_id=t_gid,status=1)
    t_freeserver=None
    t_len= len(t_sers)
    if(t_len>0):
        t_freeserver=t_sers[random.randint(0,t_len-1)]
    else:
        t_data['code']=errcode.RoomMaintain
        t_data['msg']='err serverinfo'
        return HttpResponse(ujson.dumps(t_data))

    #是否能开房间
    t_gi=GameInfo.objects.get(pk=t_gid)
    if t_gi.status==0:
        t_data['code']=errcode.RoomMaintain
        t_data['msg']='err gameinfo'
        return HttpResponse(ujson.dumps(t_data))

    game2round=webconfig.GAME_ROUND_KEY#{55:555,1000:1,2000:1}
    #房间配置是否过滤游戏,宁海（象山）不过滤
    is_filter_game=(t_gi.roundkey>0)#(t_gid in game2round.keys())
    #免费的游戏id列表
    free_games=webconfig.FREE_FEE_GAMES#[10,11,12]
    #根据openparm获取
    if is_filter_game:
        #print t_openparam,type(t_openparam),t_create_type,ujson.dumps(t_openparam)
        if t_create_type:
            tmp_openparm=eval(t_openparam.replace('u',''))
            t_openparam=ujson.dumps(tmp_openparm)
        else:
            tmp_openparm=ujson.loads(t_openparam)
        #print t_openparam
        #return
        #if t_gid in game2round :
        if t_gi.roundkey:
            #tmp_rond_key=str(game2round[t_gid])
            t_num=int(tmp_openparm.get(str(t_gi.roundkey),-1))
        #t_num=10#测试写死

    is_fee=False#房东是否扣费
    #is_fee=(t_gid in webconfig.FEE_OWNER_GAMES)#先扣房东
    try:
        is_fee=(t_gi.feetype==0)#只扣房东的

        #根据时长获取对应的点数parid_id=1,
        t_needpoint=int(t_num)

        t_r_info=RoomInfo.objects.filter(roomid=t_num).values("consumerpoint")
        if is_filter_game==1:
            t_r_info=RoomInfo.objects.filter(roomid=t_num,parid_id=t_gid).values("consumerpoint")
        #print t_gid,'--t_num--',t_num,t_r_info
        if len(t_r_info)>0:
            t_needpoint=t_r_info[0]["consumerpoint"]
        else:
            t_data['msg']="error time:"+str(t_num)
            return HttpResponse(ujson.dumps(t_data))

        #是否免费的游戏
        #if t_gid in free_games:
        if t_gi.isfree:
            t_needpoint=0

        t_data['data']['need_diamond']=t_needpoint
        #判断是否存在
        if(UserInfo.objects.filter(pk=t_uid).exists()):
            u_info=UserInfo.objects.get(pk=t_uid)
            t_point=u_info.gamepoint
            if t_point<t_needpoint:
                t_data['msg']="point not enough"
                t_data['data']['diamond']=t_point
                t_data['code']=errcode.DiamondNotEnough
                return HttpResponse(ujson.dumps(t_data))
        else:#新增
            t_data['msg']="empty uid"
            t_data['code']=errcode.UserNotExists
            return HttpResponse(ujson.dumps(t_data))

        #过滤超时的房间
        date_min=datetime.datetime.now()+datetime.timedelta(0,-webconfig.TIMEOUT_ROOM_HOUR*60*60)
        #TableInfo.objects.filter(game_status__in=t_roomstatus,create_time__lte=date_min,gameid_id=t_gid).update(status=1,game_status=3)
        handle_timeout_table(t_gid,t_gi.feetype)
        #获取玩家的当前房间列表
        cur_num=TableInfo.objects.filter(game_status__in=t_roomstatus,uid_id=t_uid,gameid_id=t_gid).count()
        if(cur_num>=webconfig.MAX_CREAT_ROOM):
            t_data['code']=errcode.RoomNumberOverFlow
            t_data['msg']="max create room :"+str(cur_num)
            t_data['params']=[cur_num,webconfig.MAX_CREAT_ROOM]
            return HttpResponse(ujson.dumps(t_data))

        recordid=str(uuid.uuid1())

        with transaction.commit_on_success():
            if is_fee:
                u_info.gamepoint-=t_needpoint
                u_info.save()

            #插入扣卡表
            tb=TableInfo()
            tb.gameid_id=t_gid
            tb.uid=u_info
            tb.time=t_num
            tb.point=t_needpoint
            tb.roomid=t_roomid
            tb.isbanker=1
            tb.playtype=t_type
            tb.recordid=recordid
            tb.server=t_freeserver
            tb.playnum=t_playnum
            tb.openparam=t_openparam
            if int(t_agent)>0 and AgentInfo.objects.filter(pk=t_agent).exists():#代理是否存在
                tb.agentid_id=int(t_agent)

            tb.create_type=t_create_type
            tb.save()

            #预扣表
            if is_fee:
                whi=WithholdInfo()
                whi.tableid_id=tb.id
                whi.uid_id=t_uid
                whi.save()

            #游戏服务器ip,port
            t_host=''
            t_port=0
            if t_freeserver:
                t_host=t_freeserver.ip
                t_port=t_freeserver.port

            t_data={'code':0,'msg':'','data':{"roomId":t_roomid,"pkid":tb.id,"diamond": u_info.gamepoint,"host":t_host,"port":t_port}}
    except Exception, e:
        #fun.add_log(e,'error')
        fun.add_log_err(traceback.format_exc())
        t_data['code']=errcode.DB_Error

    fun.add_log(t_data)

    #返回值
    response = HttpResponse(ujson.dumps(t_data))
    return  response

#用户消费，如发表情扣钱
#http://127.0.0.1:8080/api/hall/addmoneyrecord?uid=1&gameid=1&money=-10&fromtype=2&extraparam=xxxx&key=xxxx
# uid u'用户帐号'
# gameid u'游戏编号'
# money u'额度'
# fromtype u'类型'
# extraparam u'备注'
@csrf_exempt
def user_addmoneyrecord(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':[],'params':[]}
    if request.method == 'GET':
        need_keys=['uid','gameid','fromtype','money','extraparam','key']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_gid=int(t_obj['gameid'])
        t_type=int(t_obj['fromtype'])
        t_num=t_obj['money']
        t_txt=t_obj['extraparam']
        t_key=t_obj['key']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty http uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

    try:
        #判断是否重复写
        nCount=UserConsumeRecord.objects.filter(uid_id=t_uid,typeid=t_type,gameid=t_gid,requestkey=t_key).count()
        if(nCount>0):
            t_data['msg']="exists data"
            t_data['code']=errcode.DB_DataExists
            return HttpResponse(ujson.dumps(t_data))

        t_needpoint=float(t_num)

        #判断是否存在
        if(UserInfo.objects.filter(pk=t_uid).exists()):
            u_info=UserInfo.objects.get(pk=t_uid)
            u_info.gamepoint+=t_needpoint
            t_point=u_info.gamepoint
            if t_needpoint<0 and (t_point<0):
                t_data['msg']="point not enough"
                t_data['code']=errcode.DiamondNotEnough
                return HttpResponse(ujson.dumps(t_data))
        else:#新增
            t_data['msg']="empty uid"
            t_data['code']=errcode.UserNotExists
            return HttpResponse(ujson.dumps(t_data))

        with transaction.commit_on_success():
            u_info.save()
            #插入变动表
            ucr=UserConsumeRecord()
            ucr.gameid=t_gid
            ucr.typeid=t_type
            ucr.consumepoint=t_needpoint
            ucr.lastpoint=t_point
            ucr.uid_id=t_uid
            ucr.remark=t_txt
            ucr.requestkey=t_key
            ucr.save()
            t_data={'code':0,'msg':'','data':{"diamond":t_point}}
    except Exception, e:
        #fun.add_log(e,'error')
        fun.add_log_err(traceback.format_exc())
        t_data['code']=errcode.DB_Error

    fun.add_log(t_data)
    #返回值
    response = HttpResponse(ujson.dumps(t_data))
    return  response

#用户加入房间（预扣)
#http://127.0.0.1:8080/api/hall/costfront?uid=1&gameid=1&roomid=123456
# uid u'用户帐号'
# gameid u'游戏编号'
# roomid u'房间号'
@csrf_exempt
def user_joinroom(request):

    t_obj=fun.Decode_Request_MJ(request,True)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':[]}
    if request.method == 'GET':
        need_keys=['uid','gameid','roomid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_gid=t_obj['gameid']
        t_rid=t_obj['roomid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid or not t_rid:
        t_data['msg']="empty http uid"
        return HttpResponse(ujson.dumps(t_data))

    #获取房间对象
    rm_arr=TableInfo.objects.filter(roomid=t_rid,isbanker=1,gameid_id=t_gid,status=0)
    if len(rm_arr)==0:
        t_data['msg']="empty roomid"
        t_data['code']=errcode.TableNotExists
        return HttpResponse(ujson.dumps(t_data))

    #扣的金币
    tb_info=rm_arr[0]
    t_needpoint=tb_info.point
    t_pkid=tb_info.pk
    is_fee_owner=int(tb_info.gameid.feetype==0)# 只扣房东的

    #判断uid是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        u_info=UserInfo.objects.get(pk=t_uid)
        t_point=u_info.gamepoint
        if t_point<t_needpoint:
            t_data['msg']="point not enough"
            t_data['code']=errcode.DiamondNotEnough
            return HttpResponse(ujson.dumps(t_data))
    else:#新增
        t_data['msg']="empty uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

    #判断是否已预扣
    if(WithholdInfo.objects.filter(tableid_id=t_pkid,uid_id=t_uid).exists()):
        t_data['msg']="cost exists"
        t_data['code']=1
        return HttpResponse(ujson.dumps(t_data))

    #扣钱钱,是否扣全部人的
    if t_needpoint>0 and (not is_fee_owner):
        u_info.gamepoint-=t_needpoint
        u_info.save()

    #插入扣卡表
    # tb=TableInfo()
    # tb.gameid=GameInfo.objects.get(pk=t_gid)
    # tb.uid=u_info
    # tb.time=t_needpoint
    # tb.point=t_needpoint
    # tb.roomid=t_rid
    # tb.isbanker=0
    # tb.save()
    #预扣表
    whi=WithholdInfo()
    whi.tableid_id=t_pkid
    whi.uid_id=t_uid
    whi.save()

    #返回值
    t_data={'code':0,'msg':'','data':{"diamond":u_info.gamepoint,"roomId":t_rid,"gameId":t_gid,"pkid":whi.id}}

    response = HttpResponse(ujson.dumps(t_data))
    return  response

#获取玩家的所属于代理
def user_get_agent_id(u_info):
    return u_info.agentid_id or -1

#获取房间配置
#http://127.0.0.1:8080/api/hall/roominfo?uid=1&gameid=1&roomid=123456
# uid u'用户帐号'
# gameid u'游戏编号'
# roomid u'房间号'
@csrf_exempt
def user_getroominfo(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':[]}
    if request.method == 'GET':
        need_keys=['uid','gameid','roomid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_gid=t_obj['gameid']
        t_rid=t_obj['roomid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid or not t_rid:
        t_data['msg']="empty http uid"
        return HttpResponse(ujson.dumps(t_data))

    if not t_rid.isdigit():
        t_data['msg']="err roomid "+t_rid
        return HttpResponse(ujson.dumps(t_data))

    #获取房间对象,后期不按游戏过滤,按最近7天的,gameid_id=t_gid
    rm_arr=TableInfo.objects.filter(roomid=t_rid,isbanker=1).order_by("-id")
    if len(rm_arr)==0:
        t_data['msg']="empty roomid"
        t_data['code']=errcode.TableNotExists
        return HttpResponse(ujson.dumps(t_data))

    cur_rm=rm_arr[0]

    #判断uid是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        t_data['code']=0
        t_start=-1
        if cur_rm.game_time:
            t_start = DateTimeToTimetuple(cur_rm.game_time)
        own_user=cur_rm.uid#房主
        t_data['data']={'time':cur_rm.time,'createid':cur_rm.uid_id,'createname':own_user.nickname,'round':cur_rm.round,'agent_id':user_get_agent_id(cur_rm.uid),
                        'gameId':cur_rm.gameid_id,'playnum':cur_rm.playnum,'recordid':cur_rm.round and cur_rm.recordid or "",'writeid':cur_rm.recordid,'point':cur_rm.point,
                       'createTs':DateTimeToTimetuple(cur_rm.create_time), 'startTs':t_start,"gamestatus":cur_rm.game_status,"playtype":cur_rm.playtype,
                        "openparam":cur_rm.openparam,"agentId":cur_rm.agentid_id or -1,
                        'createavatar': fun.GetImgURL(request,own_user.head_img),'createtype':cur_rm.create_type or 0}#代开者
        #获取服务器地址
        t_server=cur_rm.server
        t_ip=''
        t_port=''
        if(t_server):
            t_ip=t_server.ip
            t_port=t_server.port
        t_data['data']['host']=t_ip
        t_data['data']['port']=t_port

        fun.add_log(t_data)
        return HttpResponse(ujson.dumps(t_data))
    else:#新增
        t_data['msg']="empty uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

#datetime转时间戳
def DateTimeToTimetuple(_time):
    if not _time:
        return -1
    return time.mktime(_time.timetuple())

#用户操作房间（作实，撤销)
#http://127.0.0.1:8080/api/hall/operateroom?uid=1&gameid=1&roomid=123456&status=1
# uid u'用户帐号'
# gameid u'游戏编号'
# roomid u'房间号'
#status u'状态' -1撤销，1作实
@csrf_exempt
def user_operateroom(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':[]}
    if request.method == 'GET':
        need_keys=['uid','gameid','roomid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_gid=t_obj['gameid']
        t_rid=t_obj['roomid']
        #t_pkid=t_obj['pkid']
        t_status=int(t_obj['status'])
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid or not t_rid or (t_status not in [-1,1]):
        t_data['msg']="error http data"
        return HttpResponse(ujson.dumps(t_data))

    #判断是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        u_info=UserInfo.objects.get(pk=t_uid)
        #获取房间对象
        rm_arr=TableInfo.objects.filter(roomid=t_rid,uid=u_info,status=0)
        if len(rm_arr)==0:
            t_data['msg']="empty roomid"
            return HttpResponse(ujson.dumps(t_data))
    else:#新增
        t_data['msg']="empty uid"
        return HttpResponse(ujson.dumps(t_data))

    tmp_tbinfo=rm_arr[0]
    #修改扣卡表
    tmp_tbinfo.status=t_status
    if(t_status==-1):#返回玩家的钱
        u_info.gamepoint+=tmp_tbinfo.point
        u_info.save()
    tmp_tbinfo.save()

    #返回值
    t_data={'code':0,'msg':'','data':{"diamond":u_info.gamepoint,"roomId":t_rid,"gameId":t_gid}}

    response = HttpResponse(ujson.dumps(t_data))
    return  response

#房间结束，作实有gamerecord的用户，撤销没有gamerecord的用户
#http://127.0.0.1:8080/api/hall/roomover?gameid=1&roomid=123456&status=2
# gameid u'游戏编号'
# roomid u'房间号'
# status u'解散的类型’
@csrf_exempt
def user_roomover(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':[]}
    if request.method == 'GET':
        need_keys=['gameid','roomid','status']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_gid=int(t_obj['gameid'])
        t_rid=int(t_obj['roomid'])
        t_st=int(t_obj['status'])
    elif request.method == 'POST':
        t_gid = request.POST.get('gameid',None)

    # if not (GameInfo.objects.filter(pk=t_gid).exists()):
    #     t_data['msg']="error gameid"
    #     return HttpResponse(ujson.dumps(t_data))

    #g_obj=GameInfo.objects.get(pk=t_gid)
    #判断是否存在
    try:
        if (TableInfo.objects.filter(roomid=t_rid,isbanker=1,gameid_id=t_gid,status=0).exists()):
            tb_info=TableInfo.objects.get(roomid=t_rid,isbanker=1,gameid_id=t_gid,status=0)
            #预扣的人
            tbs_arr=WithholdInfo.objects.filter(tableid_id=tb_info.id)
            #gamerecord有记录的人
            gr_arr=GameRecord.objects.filter(roomid=t_rid,gameid_id=t_gid,recordid=tb_info.recordid).values("uid")
            #redis读取
            #gr_arr=record_redis.GetTable_Palyer(t_gid,t_rid)
            # [{'uid': 1L}, {'uid': 2L}, {'uid': 3L}, {'uid': 4L}, {'uid': 1L}, {'uid': 2L}, {'uid': 3L}, {'uid': 4L}]
            ii=0#打的作实,写消息
            jj_arr=[]
            tb_point=tb_info.point
            #print(len(tbs_arr),'---tbs_arr---',len(gr_arr),gr_arr)
            with transaction.commit_on_success():
                for ii_obj in tbs_arr:
                    #print (ii_obj.uid,'---ii_obj.uid')
                    is_in=False
                    for kk_obj in gr_arr:
                        if ii_obj.uid.pk ==kk_obj['uid']:
                            ii_tb=tbs_arr[ii]
                            ii_tb.status=1
                            ii_tb.save()
                            #写到变动流水表
                            if tb_point>0:
                                cur_uid=kk_obj['uid']
                                ucr = UserConsumeRecord()
                                ucr.uid_id=cur_uid
                                ucr.gameid=t_gid
                                ucr.consumepoint=-tb_info.point
                                u_info=UserInfo.objects.get(pk=cur_uid)
                                ucr.lastpoint=u_info.gamepoint
                                ucr.typeid=1
                                ucr.remark=t_rid
                                ucr.save()

                            is_in=True
                            break
                    if not is_in:
                        jj_arr.append(ii)
                    ii+=1
                #没打的撤销，返回金币,写消息
                #print (jj_arr,'---jj_arr---',t_st)
                for jj in jj_arr:
                    ii_tb=tbs_arr[jj]
                    ii_tb.status=-1
                    ii_tb.save()
                    #返回金币
                    if tb_point>0:
                        uu_obj=ii_tb.uid
                        uu_obj.gamepoint+=tb_info.point
                        uu_obj.save()
                t_data['code']=errcode.Success

                t_data['recordid']=""
                if tb_info.round>0:#有记录返回编号，方便查询详情
                    t_data['recordid']=tb_info.recordid
                #更新房间的状态
                #TableInfo.objects.filter(roomid=t_rid,gameid_id=t_gid).update(game_status=t_st,status=1)
                tb_info.game_status=t_st
                tb_info.status=1
                tb_info.save()
            #print '--*****---',tbs_arr.game_status
        else:#新增
            t_data['msg']="empty data"
            t_data['code']=errcode.Success#DB_DataNotExists
            return HttpResponse(ujson.dumps(t_data))
    except Exception, e:
        t_data['code']=errcode.Success#errcode.DB_Error
        fun.add_log_err(traceback.format_exc())

    fun.add_log(t_data)
    response = HttpResponse(ujson.dumps(t_data))
    return  response

#房间状态更新
#http://127.0.0.1:8080/api/hall/saveroomostatus?gameid=1&roomid=123456&status=2&writeid=xxxxx
# gameid u'游戏编号'
# roomid u'房间号'
# status u'解散的类型’
# writeid u'唯一编号'
@csrf_exempt
def user_saveroomstatus(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':[]}
    if request.method == 'GET':
        need_keys=['gameid','roomid','status','writeid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_gid=int(t_obj['gameid'])
        t_rid=int(t_obj['roomid'])
        t_st=int(t_obj['status'])
        t_codeid=t_obj['writeid']
    elif request.method == 'POST':
        t_gid = request.POST.get('gameid',None)

    try:
        with transaction.commit_on_success():
            #判断是否存在
            if (TableInfo.objects.filter(roomid=t_rid,isbanker=1,gameid_id=t_gid,recordid=t_codeid).exists()):
                tb_info=TableInfo.objects.get(roomid=t_rid,isbanker=1,gameid_id=t_gid,recordid=t_codeid)
                save_agentMoney=0
                if(t_st==4 ):#开打了。。。
                    if not tb_info.game_time:#没记录过
                        tb_info.game_time=datetime.datetime.now()
                        save_agentMoney=1
                tb_info.game_status=t_st
                tb_info.save()
                if save_agentMoney:
                    save_agenttable_money(tb_info)
                t_data['code']=errcode.Success
            else:#新增
                t_data['msg']="empty data"
                t_data['code']=errcode.TableNotExists
                return HttpResponse(ujson.dumps(t_data))
    except Exception, e:
        t_data['code']=errcode.DB_Error
        fun.add_log_err(traceback.format_exc())

    fun.add_log(t_data)
    response = HttpResponse(ujson.dumps(t_data))
    return  response

#************************************用户相关操作**************************************************
#登陆验证用户(平台)
#http://127.0.0.1:8080/api/hall/platformlogin?openid=d8f33838264a11e7994f5254000d335c&nickname=qq123&pf=wx&head_img=https://www.baidu.com/img/bd_logo1.png&gender=m&phone=13800138000&ip=127.0.0.1
# openid u'用户帐号'
# nickname u'呢'
# pf u'平台'
# head_img u'头像'
# gender u'性别'
# phone u'手机号'
#ip u'玩家IP'
# "code": 0,
#     "data": {
#         "id": 1,
#         "name": "Terry",
#         "avatar": "imgs/usertext.jpg",
#         "diamond": 1234
#     }
@csrf_exempt
def user_platformlogin(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    if request.method == 'GET':
        need_keys=['openid','nickname','pt','head_img','gender','ip','phone','agent_id']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))

        t_uid = t_obj['openid']
        t_name=t_obj['nickname']
        t_pf=t_obj['pt']
        t_img=t_obj['head_img']
        t_gender = t_obj["gender"]
        t_ip = t_obj["ip"]
        t_phone=t_obj["phone"]
        t_agent=t_obj["agent_id"]
        #微信开放平台appid unionid
        t_unionid=t_obj.get('unionid',None)
        t_appid=t_obj.get('appid','')
    elif request.method == 'POST':
        t_uid = request.POST.get('openid',None)

    if not t_uid:
        t_data['msg']="empty openid"
        response = HttpResponse(ujson.dumps(t_data))
        return response

    t_point=webconfig.REGISTER_POINT#random.randint(10,100)*1000
    #判断是否存在
    if t_unionid and (UserInfo.objects.filter(unionid=t_unionid).exists()):#有了uinonid
        u_info=UserInfo.objects.get(unionid=t_unionid)
        t_point=u_info.gamepoint
    elif(UserInfo.objects.filter(uid=t_uid).exists()):#有openid,要更新unionid
        u_info=UserInfo.objects.get(uid=t_uid)
        t_point=u_info.gamepoint
        if u_info.unionid!=t_unionid:
            print u_info.unionid,'--old-t_unionid--new-',t_unionid
        u_info.unionid=t_unionid or t_uid
        u_info.appid=t_appid
    else:#新增
        u_info = UserInfo()
        u_info.uid = t_uid
        u_info.pf=t_pf
        u_info.create_ip = t_ip
        u_info.gamepoint=t_point
        u_info.appid=t_appid
        u_info.unionid=t_unionid or t_uid
        if(int(t_agent)>-1):
            u_info.agentid_id=t_agent

    u_info.gender=t_gender
    u_info.nickname=t_name
    u_info.head_img=t_img or 'websys/static/images/user.png'
    u_info.phone=t_phone

    #t_time = time.localtime(int(t_data['created']))
    u_info.login_ip=t_ip
    u_info.login_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#time.strftime('%Y-%m-%d %H:%M:%S',t_time)
    u_info.save()

    #返回值
    t_res={"id": u_info.id,"name": u_info.nickname,"avatar":  fun.GetImgURL(request,u_info.head_img),"diamond": t_point}
    # for ikey in u_info._meta.get_all_field_names():
    #     #print(ikey,'---***----',)
    #     t_res[ikey]=getattr(u_info,ikey)
    # t_res["openid"]=t_uid

    t_data['code']=0
    t_data['data']=t_res
    response = HttpResponse(ujson.dumps(t_data))
    return  response

#http://127.0.0.1:8080/api/hall/account_login?user=qq123&pwd=123&pt=wx&agentid=-1&ip=127.0.0.1
# user u'用户帐号'
# pwd u'密码'
# pt u'平台'
# agentid u'代理id',没有-1
#ip u'玩家IP'
# "code": 0,
#     "data": {
#         "id": 1
#     }
def user_accountlogin(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    if request.method == 'GET':
        need_keys=['user','pwd','pt','ip','agentid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))

        t_uid = t_obj['user']
        t_pwd=t_obj['pwd']
        t_pf=t_obj['pt']
        t_ip = t_obj["ip"]
        t_agent=t_obj["agentid"]
    elif request.method == 'POST':
        t_uid = request.POST.get('user',None)

    t_gender='m'
    t_name=t_uid

    t_phone='10086'

    if not t_uid:
        t_data['msg']="empty user"
        return HttpResponse(ujson.dumps(t_data))
    #判断是否存在
    t_point=random.randint(10,100)*100
    if(UserInfo.objects.filter(uid=t_uid,password=t_pwd).exists()):
        u_info=UserInfo.objects.get(uid=t_uid)
        t_point=u_info.gamepoint
    else:#新增
        t_data['msg']="user not exists"
        return HttpResponse(ujson.dumps(t_data))

        u_info = UserInfo()
        u_info.uid = t_uid
        u_info.password=t_pwd
        u_info.pf=t_pf
        u_info.create_ip = t_ip
        u_info.gamepoint=t_point
        if(int(t_agent)>-1):
            u_info.agentid_id=t_agent

    #u_info.gender=t_gender
    #u_info.nickname=t_name
    #u_info.head_img=t_img
    #u_info.phone=t_phone

    #t_time = time.localtime(int(t_data['created']))
    u_info.login_ip=t_ip
    u_info.login_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#time.strftime('%Y-%m-%d %H:%M:%S',t_time)
    u_info.save()

    #返回值
    t_res={"id": u_info.id,"name": u_info.nickname,"avatar":  fun.GetImgURL(request,u_info.head_img),"diamond": t_point}
    # for ikey in u_info._meta.get_all_field_names():
    #     #print(ikey,'---***----',)
    #     t_res[ikey]=getattr(u_info,ikey)
    # t_res["openid"]=t_uid

    t_data['code']=0
    t_data['data']=t_res
    response = HttpResponse(ujson.dumps(t_data))
    return  response

#http://127.0.0.1:8080/api/hall/account_register?user=qq123&pwd=123&pt=wx&agentid=-1&phone=10086&msgcode=123&friendid=facebook&ip=127.0.0.1
# user u'用户帐号'
# pwd u'密码'
# pt u'平台'
# agentid u'代理id',没有-1
# phone 手机
# msgcode 短信验证码
# friendid 好友id,没有-1
# ip u'玩家IP'
# "code": 0,
#     "data": {
#         "id": 1
#     }
def user_accountregister(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':1,'msg':'','data':{}}
    if request.method == 'GET':
        need_keys=['user','pwd','pt','ip','agentid',"phone","msgcode","friendid"]
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))

        t_uid = t_obj['user']
        t_pwd=t_obj['pwd']
        t_pf=t_obj['pt']
        t_ip = t_obj["ip"]
        t_agent=t_obj["agentid"]
        t_phone=t_obj["phone"]
        t_msgcode=t_obj["msgcode"]
        t_friendid=int(t_obj["friendid"])
    elif request.method == 'POST':
        t_uid = request.POST.get('user')

    t_gender='m'
    t_name=t_uid
    t_img='websys/static/images/user.png'

    if not t_uid:
        t_data['msg']="empty user"
        return HttpResponse(ujson.dumps(t_data))
    #判断是否存在
    t_point=random.randint(10,100)*100
    if(UserInfo.objects.filter(uid=t_uid).exists()):
        t_data['msg']="user exists"
        t_data['code']=2
        return HttpResponse(ujson.dumps(t_data))

        u_info=UserInfo.objects.get(uid=t_uid)
        t_point=u_info.gamepoint
    else:#新增
        u_info = UserInfo()
        u_info.uid = t_uid
        u_info.password=t_pwd
        u_info.pf=t_pf
        u_info.create_ip = t_ip
        u_info.gamepoint=t_point
        if(int(t_agent)>-1):
            u_info.agentid_id=t_agent

    u_info.gender=t_gender
    u_info.nickname=t_name
    u_info.head_img=t_img
    u_info.phone=t_phone
    if t_friendid>0:
        u_info.agentid_id=t_friendid

    #t_time = time.localtime(int(t_data['created']))
    u_info.login_ip=t_ip
    u_info.login_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#time.strftime('%Y-%m-%d %H:%M:%S',t_time)
    u_info.save()

    #返回值
    t_res={"id": u_info.id,"user": ''}
    # for ikey in u_info._meta.get_all_field_names():
    #     #print(ikey,'---***----',)
    #     t_res[ikey]=getattr(u_info,ikey)
    # t_res["openid"]=t_uid

    t_data['code']=0
    t_data['data']=t_res
    response = HttpResponse(ujson.dumps(t_data))
    return  response

#批量添加 用户
#http://127.0.0.1:8080/api/hall/useradd?user=test&start=100&end=200
def user_addmore(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':1,'msg':'','data':{}}
    if request.method == 'GET':
        need_keys=['user','start','end']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))

        t_uid = t_obj['user']
        t_num = int(t_obj['start'])
        t_end = int(t_obj['end'])
    elif request.method == 'POST':
        t_uid = request.POST.get('user',None)

    u_list_to_insert = list()
    for x in range(t_num,t_end):
        cur_id=t_uid+str(x)
        t_point=random.randint(10,100)*100
        u_list_to_insert.append(UserInfo(unionid=cur_id,appid='test',uid=cur_id,nickname=u'测试'+cur_id,password='123',create_ip='127.0.0.1',phone=str(t_point),gamepoint=t_point,
                                         pf='test',agentid_id=1,head_img='http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png'))
    UserInfo.objects.bulk_create(u_list_to_insert)

    t_data['code']=0
    return HttpResponse(ujson.dumps(t_data))


#获取用户信息
#http://127.0.0.1:8080/api/hall/userinfo?uid=1
# uid u'用户帐号'
# "code": 0,
#     "data": {
#         "id": 1,
#         "name": "Terry",
#         "avatar": "imgs/usertext.jpg",
#         "diamond": 1234
#     }
@csrf_exempt
def user_getinfo(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    if request.method == 'GET':
        if 'uid' not in t_obj:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty openid"
        return  HttpResponse(ujson.dumps(t_data))

    #判断是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        u_info=UserInfo.objects.get(pk=t_uid)

    else:#新增
        t_data['msg']="uid not exists "
        t_data['code']=errcode.UserNotExists
        return  HttpResponse(ujson.dumps(t_data))

    #返回值
    t_res={"id": u_info.id,"name": u_info.nickname,"avatar": fun.GetImgURL(request,u_info.head_img),"diamond": u_info.gamepoint,
           'status':u_info.status,'gender':u_info.gender,'agent_id':user_get_agent_id(u_info),'isShared':user_pre_share(t_uid)}

    t_data['code']=0
    t_data['data']=t_res
    return HttpResponse(ujson.dumps(t_data))

#获取用户统计信息
#http://127.0.0.1:8080/api/hall/getusergameinfo?uid=1&gameid=1
# uid u'用户帐号'
# "code": 0,
#     "data": {
#         [[类型,数量],[1,22],]
#     }
@csrf_exempt
def user_getgameinfo(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':[]}
    if request.method == 'GET':
        if 'uid' not in t_obj or 'gameid' not in t_obj:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_gid = t_obj['gameid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty openid"
        return  HttpResponse(ujson.dumps(t_data))

    #判断是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        #获取
        t_res=[]
        db_arr=UserExpand.objects.filter(uid_id=t_uid,game_id=t_gid).values("typeid","amount").order_by("typeid")
        for item in db_arr:
            t_res.append([item['typeid'],item['amount']])

        t_data['code']=errcode.Success
        t_data['data']=t_res
    else:
        t_data['msg']="uid not exists "
        t_data['code']=errcode.UserNotExists

    fun.add_log(t_data)
    return HttpResponse(ujson.dumps(t_data))

#获取玩家是否分享过
def user_pre_share(t_uid):
    #return 1#测试

    is_more=False#是否多次
    cur_date=datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d')

    t_key='share_%s'%(t_uid)
    rc_conn=db_redis.get_redis()
    pre_date= rc_conn.get(t_key)
    if not pre_date:#读取数据库的
        db_num=UserConsumeRecord.objects.filter(uid_id=t_uid).count()
        print(t_uid,'--user_award--from db---',db_num)
        if db_num>0:
            db_data=UserConsumeRecord.objects.filter(uid_id=t_uid).latest('create_time')
            print(db_data,db_data.create_time,type(db_data))
            pre_date=datetime.datetime.strftime(db_data.create_time,'%Y-%m-%d')
        rc_conn.set(t_key,t_uid)

    if pre_date:
        if(pre_date==cur_date) and (not is_more):#今天奖励过了
            return 1
    return 0

#用户分享游戏
#http://127.0.0.1:8080/api/hall/awarduser?uid=1&typeid=1
# uid u'用户帐号',typeid类型
# "code": 0,
#     "data": {
#         diamond:123,award:10
#     }
@csrf_exempt
def user_award(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    if request.method == 'GET':
        if 'uid' not in t_obj or 'typeid' not in t_obj:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_tid = t_obj['typeid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty openid"
        return  HttpResponse(ujson.dumps(t_data))

    #判断是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        cur_date=datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d')
        #获取上次的奖励日期
        t_key='share_%s'%(t_uid)
        rc_conn=db_redis.get_redis()
        # pre_date= rc_conn.get(t_key)
        # if not pre_date:#读取数据库的
        #     db_num=UserConsumeRecord.objects.filter(uid_id=t_uid).count()
        #     print('--user_award--from db---',db_num)
        #     if db_num>0:
        #         db_data=UserConsumeRecord.objects.filter(uid_id=t_uid).latest('create_time')
        #         print(db_data,db_data.create_time,type(db_data))
        #         pre_date=datetime.datetime.strftime(db_data.create_time,'%Y-%m-%d')


        #if(pre_date==cur_date) and (not is_more):#今天奖励过了
        if user_pre_share(t_uid):
            t_data['msg']="uid awarded "
            t_data['code']=1
        else:
            try:
                tmp_num=webconfig.SHARE_DIAMOND
                with transaction.commit_on_success():
                    uinfo=UserInfo.objects.get(pk=t_uid)
                    uinfo.gamepoint+=tmp_num
                    uinfo.save()

                    ucr=UserConsumeRecord()
                    ucr.uid_id=t_uid
                    ucr.consumepoint=tmp_num
                    ucr.lastpoint=uinfo.gamepoint
                    ucr.typeid=21
                    ucr.remark='share award'
                    ucr.isread=1
                    ucr.save()

                    rc_conn.set(t_key,cur_date)
                    t_data['code']=errcode.Success
                    t_data['data']={'diamond':uinfo.gamepoint,'award':tmp_num}
            except:
                fun.add_log_err(traceback.format_exc())
                t_data['code']=errcode.DB_Error
    else:
        t_data['msg']="uid not exists "
        t_data['code']=errcode.UserNotExists

    fun.add_log(t_data)
    return HttpResponse(ujson.dumps(t_data))

#********************************记录相关操作********************************************
#http://127.0.0.1:8080/api/hall/totalrecord?uid=4
#总记录
#uid帐号
@csrf_exempt
def user_totalrecord(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        if 'uid' not in t_obj:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))
        t_uid = t_obj['uid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))
#按游戏汇总
    t_data=[]
    gb_info=GameInfo.objects.all()
    #u_info=UserInfo.objects.get(pk=t_uid)
    t_round=0
    t_win=0
    #7天内的
    date_to=datetime.datetime.now()
    date_from=fun.GetTime_ByNow(-webconfig.GAME_RECORD_DAY)
    for ii in gb_info:
        t_num=GameRecord.objects.filter(uid_id=t_uid,gameid=ii,start_time__range=(date_from,date_to)).count()
        if t_num==0:
            continue
        t_win=GameRecord.objects.filter(uid_id=t_uid,gameid=ii,start_time__range=(date_from,date_to),score__gt=0).count()
        t_data.append({"id":ii.pk,"round":t_num,"win":t_win})
    #redisy读取
    #t_data=record_redis.GetAllRecrod(t_uid)

    t_res['code']=0
    t_res['data']=t_data
    return HttpResponse(ujson.dumps(t_res))

#http://127.0.0.1:8080/api/hall/gamerecord?uid=4&gameid=1
#记录列表
#uid帐号，gameid游戏
@csrf_exempt
def user_gamerecord(request):
    t_time=time.time()
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','gameid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = t_obj['uid']
        t_gid=int(t_obj['gameid'])
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))
    #按房间汇总
    t_data=[]
    date_from=fun.GetTime_ByNow(-webconfig.GAME_RECORD_DAY)
    date_to=datetime.datetime.now()
    # if(t_gid==0):#全部游戏
    #     tbs_info=TableInfo.objects.filter(uid_id=t_uid,create_time__range=(date_from,date_to)).order_by("-id")
    # else:
    #     tbs_info=TableInfo.objects.filter(uid_id=t_uid,create_time__range=(date_from,date_to),gameid_id=t_gid).order_by("-id")
    #print('--t_time--00---',time.time()-t_time)
    #参加的
    wh_info=WithholdInfo.objects.filter(uid_id=t_uid,create_time__gte=date_from).order_by('-id')
    t_round=0
    t_score=0
    #print('--t_time--111---',time.time()-t_time)
    for jj in wh_info:#每个房间
        cur_info=jj.tableid#房间对象
        if(t_gid>0) and (t_gid!=cur_info.gameid_id):#某个游戏
            continue

        #结束了就保存在缓存

        cur_obj=GameRecord.objects.filter(uid_id=t_uid,gameid_id=cur_info.gameid_id,roomid=cur_info.roomid,recordid=cur_info.recordid).aggregate(score=Sum("score"),num=Count("id"))
        #redis读取
        #cur_obj=record_redis.GetUserTableRecord(t_uid,cur_info.gameid_id,cur_info.roomid)

        cur_round=cur_obj["num"]
        #print cur_info.recordid,'....000000.....',cur_round
        if cur_round>0:
            t_round+=cur_round
            t_score+=cur_obj["score"]
            #房主的头像，名称
            tmp_obj={"id":cur_info.recordid,"ts":DateTimeToTimetuple(cur_info.create_time),"time":cur_info.time,"score":cur_obj["score"]}
            bank_user=UserInfo.objects.get(pk=cur_info.uid_id)
            tmp_obj['name']=bank_user.nickname
            tmp_obj['avatar']=fun.GetImgURL(request,bank_user.head_img)
            t_data.append(tmp_obj)
    #print('--t_time--222---',time.time()-t_time)
    t_res['code']=0
    t_res['data']={"roundTotal":t_round,"scoreTotal":t_score,"list":t_data}
    return HttpResponse(ujson.dumps(t_res))

#http://127.0.0.1:8080/api/hall/recorddetail?uid=4&recordid=23791531
#记录详情
#uid帐号，recordid编号
@csrf_exempt
def user_recorddetail(request):
    t_res={'code':-1,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','recordid']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))
        t_uid = t_obj['uid']
        t_recordid=t_obj['recordid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))
#分解roomid,roundid
    #t_roomid,t_roundid=kk=t_gid.split('_')

    t_data=[]
    #获取房主
    t_creatorId=-1
    tbs=TableInfo.objects.filter(recordid=t_recordid,isbanker=1).values("uid")
    if len(tbs)<=0:
        t_res['msg']='error roomid'
        t_res['code']=errcode.TableNotExists
        return HttpResponse(ujson.dumps(t_res))
    else:
        tb_info=TableInfo.objects.get(recordid=t_recordid,isbanker=1)
    t_creatorId=tbs[0]["uid"]

    t_ts=-1#开始时间
    t_secs=-1#时长
    u_info=UserInfo.objects.get(pk=t_creatorId)
    t_round=0

    gr_arr=GameRecord.objects.filter(recordid=t_recordid).values('uid_id').annotate(score=Sum('score'))
    #redis读取
    #gr_arr=record_redis.GetTableRecordList(tb_info.gameid_id,tb_info.roomid)
    #用户的呢称和头像
    #user_obj=UserInfo.objects.filter(pk__in =user_arr)
    for ii in gr_arr:
        user_obj=UserInfo.objects.get(pk=ii["uid_id"])
        t_data.append({"id":ii["uid_id"],"avatar": fun.GetImgURL(request,user_obj.head_img),"name":user_obj.nickname,"score":ii["score"]})

    t_res['code']=0
    t_res['data']={"roomId":tb_info.roomid,"creatorId":t_creatorId,"creatorName":u_info.nickname,"creatorAvatar":fun.GetImgURL(request,u_info.head_img),"gameId":tb_info.gameid_id,
                   "ts":DateTimeToTimetuple(tb_info.create_time),"time":tb_info.time,"status":tb_info.game_status,"players":t_data}
    return HttpResponse(ujson.dumps(t_res))

#*******************************************玩家反馈************************************************************
#用户反馈http://127.0.0.1:8080/api/hall/feedback?uid=1&type=1&gameid=1&name=chong&phone=10086&problem=黑游戏
#uid玩家帐号，type类型，gameid游戏id,name名称，phone手机号，problem问题
#{"msg":"","code":0}
def user_feedback(request):
    t_res={'code':0,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','type','gameid','name','phone','problem']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = t_obj['uid']
        t_type=t_obj['type']
        t_gid=t_obj['gameid']
        t_name=t_obj['name']
        t_phone=t_obj['phone']
        t_problem=t_obj['problem']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    fb=Feedback()
    if(t_uid!=''):
        fb.uid_id=int(t_uid)
    fb.gameid_id=int(t_gid)
    fb.typeid=t_type
    fb.username=t_name
    fb.phone=t_phone
    fb.problem=t_problem
    fb.save()

    t_res['code']=0

    return HttpResponse(ujson.dumps(t_res))

#用户反馈列表http://127.0.0.1:8080/api/hall/getfeedback?uid=1
#uid玩家帐号
#{"msg":"","code":0,'data':[]}
def user_getfeedback(request):
    t_res={'code':0,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid',]
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = t_obj['uid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=t_uid).exists():
        t_res['msg']='error uid'
        t_res['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_res))

    t_data=[]
    fbs=Feedback.objects.filter(uid_id=t_uid).order_by('-id')
    for item in fbs:
        ga_info=item.gameid
        # cur_obj={'status':item.get_status_display(),'type':item.get_typeid_display(),'gameid':ga_info.gamename,'problem':item.problem,
        #          'createTS':DateTimeToTimetuple(item.create_time),'replay':item.replay}
        cur_obj={'status':item.get_status_display(),'problem':item.problem, 'date':item.create_time.strftime('%Y-%m-%d'),'replay':item.replay}
        t_data.append(cur_obj)

    t_res['code']=0
    t_res['data']=t_data

    return HttpResponse(ujson.dumps(t_res))

#*************************************消息**************************************************
#房间消息
#http://127.0.0.1:8080/api/hall/getMSG?uid=1
# uid u'用户帐号'
#{"consume":[{typeid:类型，money:金额，time:时间，remark:备注,id:唯一id}],"notice":[{"msg":公告内容1,"id":唯一id,"time":时间}]}
@csrf_exempt
def user_getMSG(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    if request.method == 'GET':
        if 'uid' not in t_obj:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty http uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

    #判断用户是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        #u_info=UserInfo.objects.get(pk=t_uid)
        #获取全部的桌
        date_from=fun.GetTime_ByNow()
        date_to=datetime.datetime.now()
        #tbs=TableInfo.objects.filter(uid_id=t_uid,create_time__range=(date_from,date_to)).values("roomid","time","point","status","isbanker","create_time")
        tbs=[]
        #预扣记录
        tb_wi=WithholdInfo.objects.filter(isread=0,uid_id=t_uid,create_time__range=(date_from,date_to)).order_by('-id')
        #print t_uid,len(tb_wi),',,,,,,,,,,,,,,,,,,',date_from,date_to
        #[{typeid:类型，money:金额，time:时间，remark:备注}]
        for item in tb_wi:
            it_table=item.tableid
            #it_obj={"roomid":it_table.roomid,"time":it_table.time,"point":it_table.point,"status":item.status,"isbanker":it_table.isbanker,"create_time":DateTimeToTimetuple(item.create_time)}
            i_type=1#0预扣，1作实，2道具，3返回
            if item.status==-1:#返回的
                i_type=3
            else:
                continue
            it_obj={'id':'w_'+str(item.pk),'typeid':i_type,'money':it_table.point,
                    'time':DateTimeToTimetuple(item.create_time),'remark':str(it_table.roomid)}
            tbs.append(it_obj)
            #print it_obj
        #道具使用
        # cur_ty=2
        # ucr_data=UserConsumeRecord.objects.filter(isread=0,uid_id=t_uid,typeid=cur_ty,create_time__range=(date_from,date_to))
        # for item in ucr_data:
        #     it_obj={'id':'c_'+str(item.pk),'typeid':cur_ty,'money':item.consumepoint,'time':DateTimeToTimetuple(item.create_time),'remark':str(item.remark)}
        #     tbs.append(it_obj)
        #按时间排序
        tbs.sort(key = lambda x:x["time"],reverse=True)
        #公告的
        tbs_notice=[]
        t_data['data']={'consume':tbs,'notice':tbs_notice}
        t_data['code']=errcode.Success
        return HttpResponse(ujson.dumps(t_data))
    else:#新增
        t_data['msg']="empty uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

#看过消息
#http://127.0.0.1:8080/api/hall/readmsg?uid=1&id=1
# uid u'用户帐号'
# id u'编号'
@csrf_exempt
def user_readMSG(request):
    t_res={'code':0,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','id']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = t_obj['uid']
        t_keyid=t_obj['id']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    #判断用户是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        _preWord='w_'
        if(t_keyid.startswith(_preWord)):
            WithholdInfo.objects.filter(uid_id=t_uid,pk=t_keyid.replace(_preWord,'')).update(isread=1)
        _preWord='c_'
        if(t_keyid.startswith(_preWord)):
            UserConsumeRecord.objects.filter(uid_id=t_uid,pk=t_keyid.replace(_preWord,'')).update(isread=1)
        t_res['code']=errcode.Success
    else:#新增
        t_res['msg']="empty uid"
        t_res['code']=errcode.UserNotExists

    return HttpResponse(ujson.dumps(t_res))


#########################################其它接口##########################################################################
# price_dic={}
# price = RoomInfo.objects.filter(parid_id=1)
# for i in price:
#     price_dic[i.roomid] = i.openprice
def save_agenttable_money(table_models):
    values=0
    #agent_dic = {15: 'time_15', 20: 'time_20', 30: 'time_30', 60: 'time_60'}
    agent_id = table_models.agentid_id
    create_time = table_models.game_time
    #print agent_id,'--save_agenttable_money--',create_time
    if agent_id !=None and create_time!=None:
        #代理是否拉黑或不存在了
        if not table_models.agentid.status or len(webconfig.PLATFORM_TABLE_PRICE)==0 and not table_models.ischeck:
            print webconfig.PLATFORM_TABLE_PRICE,'--error agent save_agenttable_money--',table_models.agentid
            return
        create_date = datetime.datetime.strftime(create_time, '%Y-%m-%d')
        tmp_gameid=table_models.gameid_id
        count = AgentTableReport.objects.filter(agent_id=agent_id,create_date=create_date,gameid=tmp_gameid).count()
        game_minute = table_models.time
        #根据游戏平台获取价格
        price_dic={15:0,20:0,30:0,60:0}
        tmp_app=get_PlatformInfo_ID(tmp_gameid)
        if tmp_app and tmp_app in webconfig.PLATFORM_TABLE_PRICE:
            price_dic=webconfig.PLATFORM_TABLE_PRICE[tmp_app]
        money = price_dic[game_minute]
        if money<=0:
            print tmp_app,'--error save_agenttable_money--',table_models.gameid_id
            return
        if count !=0:
            #price = price_dic[game_minute]
            agentReport_info =AgentTableReport.objects.get(agent_id=agent_id,create_date=create_date,gameid=tmp_gameid)
            agentReport_info.allmoney += money
            agentReport_info.gameid=tmp_gameid
            exec('agentReport_info.time_'+str(game_minute)+'+= 1')
            agentReport_info.save()
            values=1
        else:
            minute_dic = {'time_15': 0, 'time_20': 0, 'time_30': 0, 'time_60': 0, 'allmoney': 0}
            minute_dic['time_'+str(game_minute)] = 1
            AgentTableReport.objects.create(agent_id=agent_id,time_15=minute_dic['time_15'],time_20=minute_dic['time_20'],time_30=minute_dic['time_30'],
                                            time_60=minute_dic['time_60'],allmoney=money,create_date=create_date,gameid=tmp_gameid)
            values=2
        agent_info=AgentInfo.objects.get(pk=agent_id)
        agent_info.allmoney += money
        agent_info.lastmoney += money
        agent_info.save()
    return values

#是否中文
def checkChinese(contents):
    zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
    match = zhPattern.search(contents)
    if match:
        return True
    return False

#实名验证
#http://127.0.0.1:8080/api/hall/yl_realname?uid=1&idcard=123456201002030405&name=%e5%b8%8c%e6%9c%9b
# uid u'用户帐号'
# idcard u'身份证号'
# name u'名字'
@csrf_exempt
def set_realname(request):
    t_res={'code':0,'msg':''}
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)
    if request.method == 'GET':
        need_keys=['uid','idcard','name']
        if len(set(need_keys)-set(t_obj.keys()))>0:
            t_res['msg']="error parms"
            return HttpResponse(ujson.dumps(t_res))

        t_uid = t_obj['uid']
        t_keyid=t_obj['idcard']
        t_name=t_obj['name']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    #身份证是否合法440123201707080012
    if not t_keyid.isdigit() or len(t_keyid)!=18 or t_keyid.startswith('0'):
        t_res['msg']="error idcard "
        return HttpResponse(ujson.dumps(t_res))

    #年月日是否对
    cur_year=int(time.strftime('%Y'))
    t_year=int(t_keyid[6:10]); t_month=int(t_keyid[10:12]);t_day=int(t_keyid[12:14])
    #print 'cur_year-t_year',cur_year-t_year,'t_year>=cur_year',t_year>=cur_year,'t_year-cur_year',t_year-cur_year
    if (cur_year-t_year)>80 or t_year>=cur_year or (t_year-cur_year)>-18 or t_month==0 or t_month>12 or t_day==0 or t_day>31:
        t_res['msg']="error idcard date:"+t_keyid[6:14]
        return HttpResponse(ujson.dumps(t_res))
    if (t_month in [1,3,5,7,8,10,12] and t_day!=31) or (t_month in [4,6,9,11] and t_day!=30) or (t_month==2 and (t_day not in [28,29])):
        t_res['msg']="error idcard day:"+t_keyid[6:14]
        return HttpResponse(ujson.dumps(t_res))

    #名字是否中文
    if not checkChinese(t_name) or len(t_name)<2 or len(t_name)>4:
        t_res['msg']="error name "
        return HttpResponse(ujson.dumps(t_res))

    #判断用户是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        u_info=UserInfo.objects.get(pk=t_uid)
        u_info.realname=t_name
        u_info.IDcard=t_keyid
        u_info.save()
        t_res['code']=errcode.Success
    else:#新增
        t_res['msg']="empty uid"
        t_res['code']=errcode.UserNotExists

    return HttpResponse(ujson.dumps(t_res))

# def test(request):
#     a = TableInfo.objects.get(id=request.GET['id'])
#     s = save_agenttable_money(a)
#     return HttpResponse(s)